//
//  CJHomeCollectionView+Move.m
//  TSDemo_List
//
//  Created by 李超前 on 2020/11/14.
//

#import "CJHomeCollectionView+Move.h"
#import <UICollectionViewCJHelper/UICollectionView+CJEnableMove.h>

@implementation CJHomeCollectionView (Move)

#pragma mark - Event
/*
*  让集合视图本身就可以通过长按来进行拖动(而不用有其他如编辑的按钮来启动拖动)
*
*  @param moveErrorBlock         移动cell整个过程出现错误的回调
*/
- (void)enableMoveWithMoveErrorBlock:(void(^ __nullable)(NSString *erorMessage))moveErrorBlock {
    [self cj_enableMoveByLongPressWithShakeEffect:YES checkSectionMoveEnableBlock:^BOOL(NSIndexPath * _Nonnull indexPath) {
        if (indexPath.section == 0) {
            return NO;
        }
        return YES;
    } checkCellMoveEnableBlock:^BOOL(NSInteger fromSection, NSInteger toSection) {
        if (toSection == 0) {
            return NO;
        }
        
        BOOL moveEnable = fromSection == toSection;
        moveEnable = YES;
        if (!moveEnable) {
            //NSString *message = @"只能在同一功能里移动";
            NSString *message = [NSString stringWithFormat:@"不能从%zd区移动到%zd区", fromSection, toSection];
            !moveErrorBlock ?: moveErrorBlock(message);
        }
        return moveEnable;
    } cellMoveCompleteBlock:^(NSIndexPath * _Nonnull sourceIndexPath, NSIndexPath * _Nonnull destinationIndexPath) {
        //从数据源中移除该数据
        CJHomeSectionDataModel *sourceSectionDataModel = [self.menuSectionDataModels objectAtIndex:sourceIndexPath.section-self.menuSectionStartIndex];
        id dataModel = [sourceSectionDataModel.values objectAtIndex:sourceIndexPath.item];
        [sourceSectionDataModel.values removeObject:dataModel];
        //并将数据插入到数据源中目标位置
        CJHomeSectionDataModel *destinationSectionDataModel = [self.menuSectionDataModels objectAtIndex:destinationIndexPath.section-self.menuSectionStartIndex];
        [destinationSectionDataModel.values insertObject:dataModel atIndex:destinationIndexPath.row];
        
        NSString *message = @"Cell移动完毕";
        !moveErrorBlock ?: moveErrorBlock(message);
    }];
}


@end
